package com.cn.zpark.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @PackageName: com.cn.zaprk
 * @ClassName: DruidUtils
 * @Description:数据库连接池工具类
 * @author: RZS
 * @date: 2022/4/2  14:21
 */
public class DruidUtils {
    // 定义数据源
    private static DataSource dataSource;

    // 初始化数据源
    static {
        Properties p = new Properties();
        InputStream ins = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

        try {
            // 加载配置文件
            p.load(ins);
            // 初始化配置数据源
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch(Exception e) {
            e.printStackTrace();
            System.out.println("初始化数据源失败");
        } finally {
            // 关闭流对象
            try {
                if(ins != null){
                    ins.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取数据库连接对象
     * @return
     */
    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭资源
     * @param conn
     * @param res
     * @param stat
     */
    public static void close(Connection conn, ResultSet res, Statement... stat){
        try {

            if(res != null){
                res.close();
            }

            for (Statement statement : stat) {
                if(statement != null){
                    statement.close();
                }

            }

            if(conn != null){
                conn.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
